package com.sky.utils;

import cn.hutool.core.util.ObjectUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.sky.po.StoredRecordPO;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Content: 腾讯云COS运存储工具
 * @Author: Asen
 * @Date: 2023/8/31 22:39
 */
@Data
@AllArgsConstructor
@Slf4j
public class TxCosUtil {
    private String endpoint;//地域
    private String accessKeyId;//id
    private String accessKeySecret;//密钥
    private String bucketName;//存储桶名称

    /**
     * 文件上传
     * @param file
     * @return
     */
    public StoredRecordPO upload(MultipartFile file){
        COSClient cosClient = null;
        //原始文件名称
        String originalFilename = "";
        //获取文件后缀
        String extension = "";
        //上传后文件名称
        String newName = "";
        try {
            //原始文件名
            originalFilename = file.getOriginalFilename();
            //获取文件后缀
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String filePath = String.valueOf(new SimpleDateFormat("yyyy/MM/dd").format(new Date()));
            newName = filePath + "/" +UUID.randomUUID() + extension;


            InputStream fileInputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //如果不设置长度会提示:No content length specified for stream data.  Stream contents will be buffered in memory and could
            objectMetadata.setContentLength(fileInputStream.available());//给流设置长度,防止内存溢出
            //默认不指定key的情况下,以文件内容的hash值为文件名
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newName, fileInputStream, objectMetadata);
            //使用cosClient调用第三方接口
            BasicCOSCredentials cred = new BasicCOSCredentials(accessKeyId, accessKeySecret);
            //clientConfig中包含了设置region,http,超时,代理set方法
            Region region = new Region(endpoint);
            ClientConfig clientConfig = new ClientConfig(region);
            //生成Cos客户端
            cosClient = new COSClient(cred, clientConfig);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(ObjectUtil.isNotNull(cosClient)) {
                cosClient.shutdown();//关闭cos释放资源
            }
        }
        //文件地址
        StringBuilder strBuilder =
                new StringBuilder("https://")
                        .append(bucketName)
                        .append(".cos.")
                        .append(endpoint)
                        .append(".myqcloud.com/")
                        .append(newName);
        //将上传的文件信息存储到表中
        StoredRecordPO storedRecordPO = new StoredRecordPO();
        storedRecordPO.setBeforeName(originalFilename);
        storedRecordPO.setAbsolutePath(strBuilder.toString());
        storedRecordPO.setSuffix(extension);
        storedRecordPO.setSize((int)file.getSize());
        return storedRecordPO;
    }

}

